#include "DigitalKeyboard.h"

DigitalKeyboard::DigitalKeyboard(QWidget *parent)
    : QWidget(parent), m_mapper(new QSignalMapper(this)) {
    // setWindowFlags(Qt::Tool | Qt::WindowStaysOnTopHint);
    setFixedSize(400, 300);

    createLayout();
    applyStyle();
}

void DigitalKeyboard::attachTo(QLineEdit *target) {
    m_target = target;
}

void DigitalKeyboard::createLayout() {
    QGridLayout *mainLayout = new QGridLayout(this);

    // 数字按钮 1-9
    for(int i=0; i<9; ++i) {
        QPushButton *btn = new QPushButton(QString::number(i+1), this);
        connect(btn, &QPushButton::clicked, m_mapper, qOverload<>(&QSignalMapper::map));
        m_mapper->setMapping(btn, QString::number(i+1));
        mainLayout->addWidget(btn, i/3, i%3);
    }

    // 底部功能按钮
    QPushButton *btn0 = new QPushButton("0", this);
    QPushButton *btnDel = new QPushButton("←", this);
    QPushButton *btnClear = new QPushButton("C", this);
    // QPushButton *btnOK = new QPushButton("✓", this);

    connect(btn0, &QPushButton::clicked, m_mapper, qOverload<>(&QSignalMapper::map));
    connect(btnDel, &QPushButton::clicked, this, &DigitalKeyboard::handleBackspace);
    connect(btnClear, &QPushButton::clicked, this, &DigitalKeyboard::handleClear);
    // connect(btnOK, &QPushButton::clicked, this, [this]{ emit inputCompleted(m_target->text()); });

    m_mapper->setMapping(btn0, "0");
    connect(m_mapper, &QSignalMapper::mappedString, this, &DigitalKeyboard::handleKeyPress);

    mainLayout->addWidget(btn0, 3, 0);
    mainLayout->addWidget(btnDel, 3, 1);
    mainLayout->addWidget(btnClear, 3, 2);
    // mainLayout->addWidget(btnOK, 3, 3);
}

void DigitalKeyboard::handleKeyPress(const QString &text) {
    if(m_target) {
        m_target->insert(text);
    }
}

void DigitalKeyboard::handleBackspace() {
    if(m_target && !m_target->text().isEmpty()) {
        m_target->backspace();
    }
}

void DigitalKeyboard::handleClear() {
    if(m_target) {
        m_target->clear();
    }
}

void DigitalKeyboard::applyStyle() {
    setStyleSheet(R"(
        DigitalKeyboard {
            background: #f0f0f0;
            border: 2px solid #d0d0d0;
            border-radius: 8px;
        }
        QPushButton {
            min-width: 60px;
            min-height: 40px;
            font: bold 18px;
            border: 1px solid #a0a0a0;
            border-radius: 4px;
            background: #ffffff;
        }
        QPushButton:hover {
            background: #e0e0e0;
        }
        QPushButton:pressed {
            background: #c0c0c0;
        }
        QPushButton[text="←"], QPushButton[text="C"] {
            background: #ff6666;
            color: white;
        }
        QPushButton[text="✓"] {
            background: #66cc66;
            color: white;
        }
    )");
}
